const Product = require('../modules/product');

exports.getIndex = (req, res, next) => {
    Product.fetchAll()
    .then(products => {
        res.render('shop/index', { 
            prods: products, 
            pageTitle: '商店', 
            path: '/' 
        });
    })
    .catch(err => console.log(err))
}

exports.getProductList = (req, res, next) => {
    Product.fetchAll()
    .then(products => {
        res.render('shop/product-list', { 
            prods: products, 
            path: '/product-list',
            pageTitle: '所有产品'
        });
    })
    .catch(err => console.log(err))
}

exports.getProductDetail = (req, res, next) => {
    const prodId = req.params.prodId;
    Product.findById(prodId)
    .then(product => {
        res.render('shop/product-detail', { 
            product: product, 
            path: '/product-list',
            pageTitle: product.title
        });
    })
    .catch(err => console.log(err))
}
exports.getCart = (req, res, next) => {
    req.user.getCart()
    .then(products => {
        const totalPrice = products.reduce((pre, prod) =>{
            return pre + prod.quantity * prod.price
        }, 0)
        res.render('shop/cart', {
            products: products,
            totalPrice,
            path: '/cart',
            pageTitle: '我的购物车'
        })
    })
    .catch(err => console.log(err))
}

exports.postCartAdd = (req, res, next) => {
    const prodId = req.body.prodId;
    req.user.addToCart(prodId)
    .then(result => {
        res.redirect('/cart');
    })
    .catch(err => console.log(err))
}

exports.postCartDelete = (req, res, next) => {
    const prodId = req.body.prodId;
    req.user.deleteFromCart(prodId)
    .then(result => {
        console.log(result);
        res.redirect('/cart');
    })
    .catch(err => console.log(err))
}

exports.postOrder = (req, res, next) => {
    req.user.addOrder()
    .then(result => {
        res.redirect('/cart');
    })
    .catch(err => console.log(err))
}

exports.getOrder = (req, res, next) => {
    req.user.getOrders()
    .then(orders => {
        res.render('shop/order', {
            path: '/order',
            pageTitle: '我的订单',
            orders
        })
    })
    .catch(err => console.log(err))
}
